package com.zsrt.devbase.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zsrt.devbase.common.annotation.HandleEntity;
import com.zsrt.devbase.common.utils.AuthCodeUtil;
import com.zsrt.devbase.common.utils.ConstantDefine;
import com.zsrt.devbase.common.utils.ShiroUtil;
import com.zsrt.devbase.common.utils.WebUtil;
import com.zsrt.devbase.dto.AccountDTO;
import com.zsrt.devbase.service.AccountService;

@Controller
@RequestMapping(value="/account")
public class AccountController extends BaseAjaxController<AccountDTO>{
	@Autowired
	private AccountService accountService;
	
	/**
	 * 
	 * @author leixin
	 * @createTime 下午5:45:35
	 * @param account
	 * @return
	 */
	@RequestMapping(value="/login")
	@ResponseBody
	public Map<String, Object> login(AccountDTO account){
		Map<String, Object> map = new HashMap<>();
		String userCode = account.getCode();
		//验证码验证的flag
		boolean flag = false;
		if (null != userCode && !"".equals(userCode)) {
			String code = (String) ShiroUtil.getSessionByKey("code");
			if (userCode.equals(code)) {
				ShiroUtil.removeSessionByKey(code);
				flag = true;
			}
		}
		//验证不通过，返回错误信息
//		if (!flag) {
//			map.put(ConstantDefine.CHECK_ERROR, "验证码错误，请填写正确的验证码");
//			return map;
//		}
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(account.getAccountCode(),account.getPassword());
		
		try {
			token.setRememberMe(true);
			subject.login(token);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			map.put(ConstantDefine.CHECK_ERROR, "用户名或密码错误，请填写正确的用户名和密码");
			return map;
		} 
		//accountService.getUserRole();
		map.put("success", "登录成功");
		List<String> sessionByKey = (List<String>) ShiroUtil.getSessionByKey(ConstantDefine.ROLE_SESSION);
		System.err.println(JSON.toJSONString(sessionByKey));
		return map;
	}
	@RequiresPermissions(value="11111")
	@RequestMapping(value="/regist")
	public ResponseEntity<Map<String, Object>> regist(@Validated AccountDTO account,BindingResult bindingResult){
		Map<String, Object> checkAndSave = accountService.checkAndSave(account);
		return WebUtil.getResponseEntity(checkAndSave);
	}
	
	/**
	 * 用户注销
	 * @author leixin
	 * @createTime 2017年5月15日
	 * @return
	 */
	@RequestMapping(value="/loginOut")
	public synchronized String loginOut(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/index";
	}
	
	/**
	 * 验证码
	 * @author leixin
	 * @createTime 2017年5月15日
	 */
	@RequestMapping(value="/code")
	public void code(){
		String code = AuthCodeUtil.getAuthCode();
		ShiroUtil.setSession("code", code);
		try {
			HttpServletResponse response = getResponse();
			ImageIO.write(AuthCodeUtil.getAuthImg(code), "JPEG", response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("图片验证码生成错误");
		}
	}

	@Override
	public String init(Model model) {
		// TODO Auto-generated method stub
		return "main";
	}

	@Override
	public Object queryByEntity(AccountDTO entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResponseEntity<Map<String, Object>> save(AccountDTO entity,
			BindingResult bindingResult) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public AccountDTO updateInit(String id) {
		// TODO Auto-generated method stub
		return null;
	}
	@HandleEntity(fillCreator=true)
	@Override
	public ResponseEntity<Map<String, Object>> update(AccountDTO entity,
			BindingResult bindingResult) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResponseEntity<Map<String, Object>> delete(List<String> id) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@RequestMapping(value="/selectByTest")
	public List<AccountDTO> selectByTest(AccountDTO accountDTO) {
		List<AccountDTO> selectByTest = accountService.selectByTest(accountDTO);
		System.err.println(JSON.toJSONString(selectByTest));
		return selectByTest;
		
	}
}
